package miniMVC
{
	import miniMVC.i.IController;
	import miniMVC.patterns.Listener;
	
	/**
	 * 控制器
	 * 此对象同view,model一样也是有状态的，用的时候必须像view一样先初始
	 * @author Pelephone
	 * @website http://cnblogs.com/pelephone
	 */
	public class Controller extends Listener implements IController
	{
		/** 绑定访问 <String,Vector.<Function>> */
		protected var listenerHm:Object;
		
		/**
		 * 通过名字构造控制器
		 * @param controllerName
		 */
		public function Controller(controllerName:String)
		{
			super(controllerName);
			listenerHm = {};
		}
		
		public function execute(visitNote:String, argArray:Array=null):void
		{
			callVisiters(visitNote,argArray);
		}
		
		/**
		 * 添加访问绑定
		 * @param visitNote
		 * @param listener
		 */
		protected function addVisiterListener(visitNote:String,listener:Function):void
		{
			var ls:Vector.<Function> = listenerHm[visitNote] as Vector.<Function>;
			if(!ls) ls = listenerHm[visitNote] = new Vector.<Function>();
			ls.push(listener);
//			listenerHm.addEventListener(visitNote,listener);
		}
		
		/**
		 * 移除访问监听绑定
		 * @param visitNote
		 * @param listener
		 */
		protected function removeVisiterListener(visitNote:String,listener:Function):void
		{
			var ls:Vector.<Function> = listenerHm[visitNote] as Vector.<Function>;
			if(!ls) return;
			var fid:int = ls.indexOf(listener);
			ls.splice(fid,1);
		}
		
		/**
		 * 移除某访问消息的所有监听者
		 * @param visitNote
		 */
		protected function removeVisterNote(visitNote:String):void
		{
			listenerHm[visitNote] = null;
		}
		
		protected function callVisiters(type:String,argArray:Array):void
		{
			var listeners:Vector.<Function> = listenerHm[type] as Vector.<Function>;
			for each (var listener:Function in listeners) 
			{
				listener.apply(null,argArray);
			}
		}
	}
}